<!--
  题目列表页面
-->
<template>
  <div class="question-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>题目管理</h1>
        <p>管理和查看所有题目</p>
      </div>
      <div class="header-right">
        <el-button
          type="primary"
          :icon="Plus"
          @click="createQuestion"
          v-if="authStore.hasPermission('question:write')"
        >
          创建题目
        </el-button>
        <el-button
          :icon="Upload"
          @click="showImportDialog = true"
          v-if="authStore.hasPermission('question:write')"
        >
          批量导入
        </el-button>
      </div>
    </div>

    <!-- 高级搜索 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="题库">
              <el-select
                v-model="searchForm.question_bank"
                placeholder="选择题库"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="bank in questionBanks"
                  :key="bank.id"
                  :label="bank.name"
                  :value="bank.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="题目类型">
              <el-select
                v-model="searchForm.question_type"
                placeholder="选择类型"
                clearable
                style="width: 100%"
              >
                <el-option label="单选题" value="single_choice" />
                <el-option label="多选题" value="multiple_choice" />
                <el-option label="判断题" value="true_false" />
                <el-option label="填空题" value="fill_blank" />
                <el-option label="简答题" value="essay" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="难度">
              <el-select
                v-model="searchForm.difficulty"
                placeholder="选择难度"
                clearable
                style="width: 100%"
              >
                <el-option label="简单" value="easy" />
                <el-option label="中等" value="medium" />
                <el-option label="困难" value="hard" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="分值范围">
              <el-slider
                v-model="searchForm.points_range"
                :min="0"
                :max="20"
                :step="1"
                range
                show-stops
                style="margin-top: 8px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="标签">
              <el-select
                v-model="searchForm.tags"
                multiple
                filterable
                allow-create
                placeholder="选择或输入标签"
                style="width: 100%"
              >
                <el-option
                  v-for="tag in availableTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12">
            <el-form-item label="关键词">
              <el-input
                v-model="searchForm.keyword"
                placeholder="搜索题目内容、选项或答案"
                clearable
                @keyup.enter="loadQuestions"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="4">
            <el-form-item>
              <div class="search-actions">
                <el-button type="primary" @click="loadQuestions">
                  搜索
                </el-button>
                <el-button @click="resetSearch">重置</el-button>
                <el-button
                  type="success"
                  :icon="Download"
                  @click="exportQuestions"
                  :disabled="questions.length === 0"
                >
                  导出
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 题目表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="header-left">
          <span class="table-title">题目列表</span>
          <span class="table-info">
            共 {{ total }} 道题目
            <span v-if="selectedQuestions.length > 0">
              ，已选择 {{ selectedQuestions.length }} 道
            </span>
          </span>
        </div>
        <div class="header-right">
          <el-button
            type="danger"
            :icon="Delete"
            @click="showBatchDeleteDialog = true"
            :disabled="selectedQuestions.length === 0"
            v-if="authStore.hasPermission('question:delete')"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <el-table
        :data="questions"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="题目" min-width="300">
          <template #default="{ row }">
            <div class="question-cell">
              <div class="question-content">
                {{ truncateText(stripHtml(row.content), 150) }}
              </div>
              <div class="question-options" v-if="showTableOptions(row)">
                <div class="options-preview">
                  {{ getOptionsPreview(row) }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100" sortable="custom">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.question_type)" size="small">
              {{ getTypeText(row.question_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="难度" width="80" sortable="custom">
          <template #default="{ row }">
            <el-tag :type="getDifficultyTagType(row.difficulty)" size="small">
              {{ getDifficultyText(row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分值" width="80" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.points }}分</span>
          </template>
        </el-table-column>
        <el-table-column label="题库" width="150">
          <template #default="{ row }">
            <el-link type="primary" @click="goToBank(row.question_bank)">
              {{ row.question_bank_name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="标签" width="200">
          <template #default="{ row }">
            <div class="tags-cell">
              <el-tag
                v-for="tag in (row.tags || []).slice(0, 3)"
                :key="tag"
                size="small"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
              <span v-if="row.tags && row.tags.length > 3" class="more-tags">
                +{{ row.tags.length - 3 }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                text
                type="primary"
                size="small"
                @click="viewQuestion(row)"
              >
                查看
              </el-button>
              <el-button
                text
                size="small"
                @click="editQuestion(row)"
                v-if="canEditQuestion(row)"
              >
                编辑
              </el-button>
              <el-button
                text
                type="danger"
                size="small"
                @click="deleteQuestion(row)"
                v-if="canDeleteQuestion(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="total"
          :page-sizes="[20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadQuestions"
          @current-change="loadQuestions"
        />
      </div>
    </el-card>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="批量导入题目"
      width="600px"
    >
      <div class="import-content">
        <el-steps :active="importStep" align-center>
          <el-step title="选择文件" />
          <el-step title="数据预览" />
          <el-step title="导入完成" />
        </el-steps>

        <div class="step-content">
          <!-- 步骤1: 选择文件 -->
          <div v-if="importStep === 0" class="file-upload-step">
            <el-upload
              class="upload-area"
              drag
              accept=".xlsx,.xls,.csv"
              :auto-upload="false"
              :on-change="handleFileChange"
              :limit="1"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 Excel、CSV 格式，文件大小不超过 10MB
                </div>
              </template>
            </el-upload>

            <div class="template-download">
              <el-link type="primary" @click="downloadTemplate">
                下载导入模板
              </el-link>
            </div>
          </div>

          <!-- 步骤2: 数据预览 -->
          <div v-else-if="importStep === 1" class="preview-step">
            <el-table :data="previewData" height="300">
              <el-table-column prop="content" label="题目内容" />
              <el-table-column prop="question_type" label="类型" width="100" />
              <el-table-column prop="difficulty" label="难度" width="80" />
              <el-table-column prop="points" label="分值" width="80" />
            </el-table>
          </div>

          <!-- 步骤3: 导入完成 -->
          <div v-else class="result-step">
            <el-result
              :icon="importResult.success ? 'success' : 'error'"
              :title="importResult.title"
              :sub-title="importResult.message"
            >
              <template #extra>
                <el-button type="primary" @click="showImportDialog = false">
                  完成
                </el-button>
              </template>
            </el-result>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button
            v-if="importStep > 0"
            @click="importStep--"
          >
            上一步
          </el-button>
          <el-button
            v-if="importStep < 2"
            type="primary"
            :disabled="importStep === 0 && !importFile"
            :loading="importLoading"
            @click="nextImportStep"
          >
            {{ importStep === 1 ? '开始导入' : '下一步' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量删除确认对话框 -->
    <el-dialog
      v-model="showBatchDeleteDialog"
      title="批量删除确认"
      width="400px"
    >
      <p>确定要删除选中的 {{ selectedQuestions.length }} 道题目吗？此操作不可恢复！</p>
      <template #footer>
        <el-button @click="showBatchDeleteDialog = false">取消</el-button>
        <el-button
          type="danger"
          :loading="batchDeleteLoading"
          @click="confirmBatchDelete"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores'
import {
  getQuestions,
  getQuestionBanks,
  deleteQuestion as apiDeleteQuestion,
  batchDeleteQuestions,
  batchImportQuestions
} from '@/api/questions'
import type { Question, QuestionBank } from '@/types'
import {
  Plus,
  Upload,
  Download,
  Delete,
  UploadFilled
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const questions = ref<Question[]>([])
const questionBanks = ref<QuestionBank[]>([])
const selectedQuestions = ref<Question[]>([])
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  question_bank: '',
  question_type: '',
  difficulty: '',
  tags: [] as string[],
  keyword: '',
  points_range: [0, 20] as [number, number]
})

// 分页和排序
const pagination = reactive({
  page: 1,
  page_size: 20
})
const sortField = ref('')
const sortOrder = ref('')

// 导入相关
const showImportDialog = ref(false)
const importStep = ref(0)
const importFile = ref<File | null>(null)
const importLoading = ref(false)
const previewData = ref<any[]>([])
const importResult = reactive({
  success: false,
  title: '',
  message: ''
})

// 批量删除
const showBatchDeleteDialog = ref(false)
const batchDeleteLoading = ref(false)

// 可用标签
const availableTags = computed(() => {
  const allTags = new Set<string>()
  questions.value.forEach(q => {
    q.tags?.forEach(tag => allTags.add(tag))
  })
  return Array.from(allTags)
})

// 加载题库列表
const loadQuestionBanks = async () => {
  try {
    const response = await getQuestionBanks({ page_size: 100 })
    questionBanks.value = response.data.results
  } catch (error) {
    console.error('Failed to load question banks:', error)
  }
}

// 加载题目列表
const loadQuestions = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.page_size,
      search: searchForm.keyword || undefined,
      question_bank: searchForm.question_bank || undefined,
      question_type: searchForm.question_type || undefined,
      difficulty: searchForm.difficulty || undefined,
      tags: searchForm.tags.length > 0 ? searchForm.tags : undefined,
      points_min: searchForm.points_range[0],
      points_max: searchForm.points_range[1]
    }

    if (sortField.value) {
      params.ordering = sortOrder.value === 'ascending'
        ? sortField.value
        : `-${sortField.value}`
    }

    const response = await getQuestions(params)
    questions.value = response.data.results
    total.value = response.data.count
  } catch (error) {
    console.error('Failed to load questions:', error)
    ElMessage.error('加载题目失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    question_bank: '',
    question_type: '',
    difficulty: '',
    tags: [],
    keyword: '',
    points_range: [0, 20]
  })
  pagination.page = 1
  loadQuestions()
}

// 处理选择变化
const handleSelectionChange = (selection: Question[]) => {
  selectedQuestions.value = selection
}

// 处理排序变化
const handleSortChange = ({ prop, order }: any) => {
  sortField.value = prop || ''
  sortOrder.value = order || ''
  loadQuestions()
}

// 查看题目详情
const viewQuestion = (question: Question) => {
  router.push(`/questions/questions/${question.id}`)
}

// 编辑题目
const editQuestion = (question: Question) => {
  router.push(`/questions/questions/${question.id}/edit`)
}

// 删除题目
const deleteQuestion = async (question: Question) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这道题目吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await apiDeleteQuestion(question.id)
    ElMessage.success('题目删除成功')
    loadQuestions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete question:', error)
      ElMessage.error('删除题目失败')
    }
  }
}

// 确认批量删除
const confirmBatchDelete = async () => {
  batchDeleteLoading.value = true
  try {
    const questionIds = selectedQuestions.value.map(q => q.id)
    await batchDeleteQuestions({ question_ids: questionIds })
    ElMessage.success(`成功删除 ${questionIds.length} 道题目`)
    selectedQuestions.value = []
    showBatchDeleteDialog.value = false
    loadQuestions()
  } catch (error) {
    console.error('Failed to batch delete questions:', error)
    ElMessage.error('批量删除失败')
  } finally {
    batchDeleteLoading.value = false
  }
}

// 创建题目
const createQuestion = () => {
  router.push('/questions/questions/create')
}

// 跳转到题库
const goToBank = (bankId: number) => {
  router.push(`/questions/banks/${bankId}`)
}

// 导出题目
const exportQuestions = () => {
  ElMessage.info('导出功能开发中...')
}

// 下载模板
const downloadTemplate = () => {
  ElMessage.info('模板下载功能开发中...')
}

// 处理文件变化
const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

// 下一步导入
const nextImportStep = async () => {
  if (importStep.value === 0) {
    // 进入预览步骤
    if (!importFile.value) return

    // TODO: 解析文件并预览数据
    importStep.value++
  } else if (importStep.value === 1) {
    // 执行导入
    importLoading.value = true
    try {
      // TODO: 实际导入逻辑
      await new Promise(resolve => setTimeout(resolve, 2000)) // 模拟导入

      Object.assign(importResult, {
        success: true,
        title: '导入成功',
        message: `成功导入 10 道题目`
      })
      importStep.value++
      loadQuestions()
    } catch (error) {
      Object.assign(importResult, {
        success: false,
        title: '导入失败',
        message: '导入过程中发生错误，请检查文件格式'
      })
      importStep.value++
    } finally {
      importLoading.value = false
    }
  }
}

// 权限检查
const canEditQuestion = (question: Question) => {
  return authStore.hasPermission('question:write') &&
         (question.creator === authStore.user?.id || authStore.hasRole('admin'))
}

const canDeleteQuestion = (question: Question) => {
  return authStore.hasPermission('question:delete') &&
         (question.creator === authStore.user?.id || authStore.hasRole('admin'))
}

// 工具函数
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

const stripHtml = (html: string) => {
  return html.replace(/<[^>]*>/g, '')
}

const truncateText = (text: string, maxLength: number) => {
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

const getTypeText = (type: string) => {
  const types: Record<string, string> = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题',
    essay: '简答题'
  }
  return types[type] || type
}

const getTypeTagType = (type: string) => {
  const types: Record<string, string> = {
    single_choice: 'primary',
    multiple_choice: 'success',
    true_false: 'warning',
    fill_blank: 'info',
    essay: 'danger'
  }
  return types[type] || 'info'
}

const getDifficultyText = (difficulty: string) => {
  const difficulties: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return difficulties[difficulty] || difficulty
}

const getDifficultyTagType = (difficulty: string) => {
  const types: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

const showTableOptions = (question: Question) => {
  return ['single_choice', 'multiple_choice'].includes(question.question_type)
}

const getOptionsPreview = (question: Question) => {
  if (!question.options || !Array.isArray(question.options)) return ''
  return question.options
    .slice(0, 2)
    .map((opt: any, index: number) => `${String.fromCharCode(65 + index)}. ${opt}`)
    .join(' | ')
}

// 页面挂载时加载数据
onMounted(() => {
  loadQuestionBanks()
  loadQuestions()
})
</script>

<style scoped lang="scss">
.question-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 24px;

    .header-left {
      h1 {
        font-size: 28px;
        color: var(--el-text-color-primary);
        margin: 0 0 8px 0;
      }

      p {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin: 0;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .search-card {
    margin-bottom: 24px;

    .search-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }
  }

  .table-card {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .header-left {
        .table-title {
          font-size: 18px;
          font-weight: 600;
          color: var(--el-text-color-primary);
          margin-right: 12px;
        }

        .table-info {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }

    .question-cell {
      .question-content {
        font-size: 14px;
        color: var(--el-text-color-primary);
        line-height: 1.5;
        margin-bottom: 8px;
      }

      .question-options {
        .options-preview {
          font-size: 12px;
          color: var(--el-text-color-regular);
          background: var(--el-fill-color-light);
          padding: 4px 8px;
          border-radius: 4px;
        }
      }
    }

    .tags-cell {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;

      .tag-item {
        margin-right: 4px;
      }

      .more-tags {
        font-size: 12px;
        color: var(--el-text-color-placeholder);
      }
    }

    .action-buttons {
      display: flex;
      gap: 8px;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }

  .import-content {
    .step-content {
      margin-top: 24px;

      .file-upload-step {
        .template-download {
          text-align: center;
          margin-top: 16px;
        }
      }

      .preview-step {
        // 预览样式
      }

      .result-step {
        // 结果样式
      }
    }
  }

  .dialog-footer {
    text-align: right;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .question-list {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;

      .header-right {
        justify-content: flex-start;
      }
    }

    .search-card {
      .search-actions {
        justify-content: flex-start;
      }
    }

    .table-card {
      .table-header {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
      }
    }
  }
}
</style>